import { View, Image, Button } from '@tarojs/components'
import Taro, { useLoad, useRouter } from '@tarojs/taro'
import { OsIcon, OsBadge } from 'ossaui'
import './detail.scss'
import { useMemo, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'

export default function Index() {
  const router = useRouter()
  const [item, setItem] = useState(null)
  const dispatch = useDispatch()
  const carList = useSelector(state => state.carList)
  useLoad(() => {
    Taro.request({
      url: 'http://localhost:3000/list/' + router.params.id
    }).then(res => {
      console.log(res)
      setItem(res.data)
    })
  })

  const onAddCar = () => {
    dispatch({
      type: 'ADD_CAR',
      payload: item
    })
  }

  const allCount = useMemo(() => {
    return carList.reduce((prev, next) => {
      return prev + next.count
    }, 0)
  }, [carList])

  return (
    <View className='index'>
      <Image src={item?.image} />
      <View>{item?.title}</View>
      <View>¥ {item?.price}</View>
      <View className='footer'>
        <OsBadge type='info' info={allCount}>
          <OsIcon
            type='detail-cart'
            className='icon'
            customStyle={{ verticalAlign: "top" }}
            onClick={() => {
              Taro.switchTab({
                url: '/pages/car/car'
              })
            }}
          ></OsIcon>
        </OsBadge>
        <Button onClick={onAddCar}>加入购物车</Button>

      </View>
    </View>
  )
}
